package io.renren.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.modules.PCguanli.dao.LineDao;
import io.renren.modules.PCguanli.dao.LineDeptDao;
import io.renren.modules.PCguanli.entity.LineDeptEntity;
import io.renren.modules.PCguanli.entity.LineEntity;
import io.renren.modules.app.dao.UserDao;
import io.renren.modules.app.dao.UserRegistrationDao;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.entity.UserRegistrationEntity;
import io.renren.modules.app.mapper.LineMapper;
import io.renren.modules.app.mapper.UserRegistrationMapper;
import io.renren.modules.app.service.RegistratiService;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

@Service("RegistratiService")
public class RegistratiServiceImpl extends ServiceImpl<UserRegistrationDao, UserRegistrationEntity> implements RegistratiService {


    @Autowired
    private UserRegistrationDao userRegistrationDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private LineDao lineDao;
    @Autowired
    private LineDeptDao lineDeptDao;
    @Autowired
    private UserRegistrationMapper userRegistrationMapper;
    @Autowired
    private LineMapper lineMapper;


    @Override
    public UserRegistrationEntity updateresInfo(int userId, String way, String carrythings, String tonnage, String carshop, String time, int recordId,String name,String iphone) {
        UserEntity useEntity = userDao.findByUserId(userId);
        UserRegistrationEntity userRegistrationEntity = userRegistrationDao.selectOne(new LambdaQueryWrapper<UserRegistrationEntity>()
                .eq(UserRegistrationEntity::getRecordid,recordId));
        if (userRegistrationEntity == null) {
            throw new RRException("请先车检");
        }
        else if(userRegistrationEntity.getState().equals("1")){
            throw new RRException("已叫号状态无法更改报到资料");
        }
        else if(userRegistrationEntity.getState().equals("2")){
            throw new RRException("排队中状态无法更改报到资料");
        }
        else if(userRegistrationEntity.getState().equals("3")){
            throw new RRException("已报到状态无法更改报到资料");
        }
        else if(userRegistrationEntity.getState().equals("4")||userRegistrationEntity.getState().equals("6")||userRegistrationEntity.getState().equals("7")){
            if(name.isEmpty() && iphone.isEmpty()){

            }
            else {
                UserEntity user = userDao.selectOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getIPhone, iphone)
                        .eq(UserEntity::getName, name)
                        .eq(UserEntity::getClassification, 0));
                if (user == null) {
                    throw new RRException("助手资料有误或尚未注册");
                }
                userRegistrationEntity.setDatcherid(user.getUser_id());
                user.setDriverId(userId);
            }
            userRegistrationEntity.setCarnumber(useEntity.getCarnumber());
            userRegistrationEntity.setWay(way);
            userRegistrationEntity.setCarrythings(carrythings);
            userRegistrationEntity.setTonnage(tonnage);
            userRegistrationEntity.setCarshop(carshop);
            userRegistrationEntity.setTime(time);
            userRegistrationEntity.setDriverid(userId);

            if(userRegistrationEntity.getState().equals("7")){
                LocalDateTime now = LocalDateTime.now();
                // 格式化日期时间为'yyyyMMdd'格式
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                String datePrefix = now.format(formatter);
                String num = userRegistrationEntity.getRecordid().toString();
                userRegistrationEntity.setOrderNumber("TS"+datePrefix+num);
            }
            userRegistrationEntity.setState("4");
            userRegistrationDao.updateById(userRegistrationEntity);
 /*          UpdateWrapper<UserRegistrationEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("recordID", recordId);
            userRegistrationMapper.update(userRegistrationEntity, updateWrapper);
  */

            //更新LineEntity
            useEntity.setCardealer(carshop);
            userDao.updateById(useEntity);
            LineDeptEntity lineDeptEntity = lineDeptDao.selectOne(new LambdaQueryWrapper<LineDeptEntity>().eq(LineDeptEntity::getDeptName,userRegistrationEntity.getPurchaseplant()));
            int deptId = lineDeptEntity.getDeptId();
            LineEntity lineEntity = lineDao.selectOne(new LambdaQueryWrapper<LineEntity>().eq(LineEntity::getDeptId,deptId)
                    .eq(LineEntity::getIdcard,useEntity.getID()));//根据厂商和身份证找到排队记录
            if(lineEntity ==null){       //说明第一次来该厂，还从未提交报到资料
                LineEntity lineEntity1 = new LineEntity();
                lineEntity1.setIdcard(useEntity.getID());
                lineEntity1.setCarshop(carshop);
                if(userRegistrationEntity.getModel().equals("平板P")){
                    lineEntity1.setLineorder(1);
                }
                else{
                    lineEntity1.setLineorder(2);
                }
                lineEntity1.setRegistertime(userRegistrationEntity.getTime());
                lineEntity1.setRegisterstate(userRegistrationEntity.getState());
                lineEntity1.setDeptId(deptId);
                lineDao.insert(lineEntity1);
            }
            else{//在该厂曾经排过队，覆盖曾经的排队信息
                lineEntity.setIdcard(useEntity.getID());
                lineEntity.setCarshop(carshop);
                if(userRegistrationEntity.getModel().equals("平板P")){
                    lineEntity.setLineorder(1);
                }
                else{
                    lineEntity.setLineorder(2);
                }
                lineEntity.setRegistertime(userRegistrationEntity.getTime());
                lineEntity.setRegisterstate(userRegistrationEntity.getState());
                lineEntity.setDeptId(deptId);
                lineDao.updateById(lineEntity);
            }
        }
        // 返回更新后的用户信息

            return userRegistrationEntity;
        }



    @Override
    public UserRegistrationEntity vehicleinspect(int userId, String model, String purchaseplant,String picture,String emissionstandard) {
        if(picture == null){
            throw new RRException("请签字确认");
        }
        UserEntity userEntity =userDao.findByUserId(userId);
        LocalDateTime endTime = LocalDateTime.now(); // 获取当前时间
        LocalDateTime startTime = endTime.minus(3, ChronoUnit.HOURS); // 计算出当前时间之前的3小时的时间

        UserRegistrationEntity userRegistrationEntity1 = userRegistrationDao.selectOne(new LambdaQueryWrapper<UserRegistrationEntity>()
                .eq(UserRegistrationEntity::getDriverid,userId)
                .eq(UserRegistrationEntity::getPurchaseplant,purchaseplant)
                .ne(UserRegistrationEntity::getState,"5")
                .between(UserRegistrationEntity::getTime, startTime, endTime));
        if(userRegistrationEntity1!=null){
            throw new RRException("同厂区3小时内不得重复车检");
        }
        userEntity.setEmissionstandard(emissionstandard);
        userDao.updateById(userEntity);
        UserRegistrationEntity userRegistrationEntity = new UserRegistrationEntity();
        userRegistrationEntity.setState("7");
        userRegistrationEntity.setModel(model);
        userRegistrationEntity.setPurchaseplant(purchaseplant);
        userRegistrationEntity.setPicture(picture);
        userRegistrationEntity.setEmissionstandard(emissionstandard);
        userRegistrationEntity.setDriverid(userId);
        userRegistrationDao.insert(userRegistrationEntity);
        return userRegistrationEntity;

    }
}

